/*
 * @Author: your name
 * @Date: 2021-12-08 09:25:58
 * @LastEditTime: 2022-01-11 09:10:49
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \lliyuwei2\admin\src\router\RouterView.js
 */
import React, { Suspense, useMemo, useState } from "react";
import { Switch, Redirect, Route, useLocation } from "react-router-dom";
import loading from "../assets/image/load.gif";
import Login from "../pages/login";
import Cookie from "js-cookie";
import Register from "../pages/register";
const RouterView = (props) => {
  const userData = window.sessionStorage.getItem("userData");
  const token = Cookie.get("token");
  const location = useLocation();
  const [pathname, setPathname] = useState(location.pathname);
  const { routes } = props;

  useMemo(async () => {
    await setPathname(location.pathname);
    if (location.pathname === "/login" || location.pathname === "/register") {
      removeInfo();
    }
    if (!token && location.pathname === "/") {
      window.location.href = "/login";
      removeInfo();
    }
  }, [location.pathname]);
  const removeInfo = () => {
    if (token) {
      Cookie.remove("token");
    }
    window.sessionStorage.removeItem("userData");
  };
  return (
    <Suspense
      fallback={
        <div className="loading">
          <img src={loading} alt="" />
        </div>
      }
    >
      <Switch>
        {token && userData ? (
          routes?.length &&
          routes.map((item, index) => {
            return item.path ? (
              <Route
                exact={false}
                key={index}
                path={item.path}
                render={(props) => {
                  if (item.children) {
                    return <item.component {...props} routes={item.children}></item.component>;
                  } else {
                    return <item.component {...props}></item.component>;
                  }
                }}
              />
            ) : (
              <Redirect from={item.from} to={item.to} exact key={index} />
            );
          })
        ) : pathname === "/register" ? (
          <Route to="/register" component={Register}></Route>
        ) : (
          <Route to="/login" component={Login}></Route>
        )}
      </Switch>
    </Suspense>
  );
};

export default RouterView;
